package com.yihuchess.bluetoothConnect;

import android.Manifest;
import android.os.Handler;
import android.os.Bundle;
import android.os.Build;
import android.app.Activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import android.bluetooth.BluetoothProfile;

import com.nbchess.api.BtBoardListener;
import com.nbchess.api.BtBoardInterface;
import com.nbchess.ublservice.UBLService;
import com.yihuchess.bluetoothConnect.ArrayAdapter;
import com.yihuchess.bluetoothConnect.BTBoardConnectActivity;
import com.yihuchess.bluetoothConnect.BtKeyListener;
import com.yihuchess.bluetoothConnect.BTBoardConnectActivity.Device;
import com.yihuchess.simplechess.R;


public class BtInterfaceMananger  {

    private static final String TAG = "BtInterfaceMananger";

    public final static int BT_BOARD_CONNECT_CODE = 5;
    public final static String BtBoardName = "BtBoardName";
    public static int mScanCnt = 10;
    public static int needReconnect = 0;
    public static int ledDegree = 0;

    public static BtBoardInterface mBtBoardInterface = null;
    public static BtKeyListener mBtKeyCaller = null;
    public static UBLService mUBLService = null;
    private Device mDevice = null;
    public Handler checkHandler = null;
    public Handler settingHandler = null;
    public static Activity instance = null;
    public static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;

    static Button mConnectBtBoard;
    //Button mBtBoardSetting;
    public SeekBar lightSeekBar;
    static public BtInterfaceMananger myMananger = null;


    static public BtInterfaceMananger init(Activity myActivity, Button myBtBoard) {
        myMananger = new BtInterfaceMananger();
        mConnectBtBoard = (Button)myBtBoard;
        needReconnect = 1;
        mBtKeyCaller = null;
        instance = myActivity;
        myMananger.reconnectThread();
        return myMananger;
    }

    public void onBtResume() {
        mBtKeyCaller = null;
        
		if ((mUBLService == null) || (mDevice == null)) {
		    mUBLService = BTBoardConnectActivity.getUBLService();
			mDevice = (Device) BTBoardConnectActivity.getBtDevice();

		    if (mUBLService != null && mDevice != null) {
			    mBtBoardInterface = new BtBoardInterface(mUBLService, mDevice.address);
			    mBtBoardInterface.setListener(mBtBoardListener);
                mBtBoardInterface.setBoardSizeAndType(19, 3);
	            mBtBoardInterface.clearBoardLight();
                //mBtBoardInterface.processSn(0);
                //mBtBoardInterface.sendScBytes();
		    } else { 
                mBtBoardInterface = null;
            }
        } 

        if (mConnectBtBoard == null) {
            return;
        }
        if (mBtBoardInterface == null) {
            if (mDevice == null) {
                if (mScanCnt > 0) {
                    mConnectBtBoard.setText(R.string.bt_state_connecting);
                } else {
                    mConnectBtBoard.setText(R.string.bt_state_please_connect);
                }
            }
            mConnectBtBoard.setBackgroundResource(R.drawable.bt_button);
        } else {
            needReconnect = 1;
            mConnectBtBoard.setText(R.string.bt_state_connected);
            mConnectBtBoard.setBackgroundResource(R.drawable.bt_button_connected);
        }
    }

    public void onButtonInit() {
        if (mBtBoardInterface != null) {
            mBtBoardInterface.setBoardSizeAndType(19, 3);
            mBtBoardInterface.clearBoardLight();
        }
    }

    public Runnable checkDeviceThread = new Runnable() {  
        public void run() {  
            int finded = 0;

            if (BTBoardConnectActivity.isScanning()) {
                if (BTBoardConnectActivity.getBtDevice() != null) {
                    finded = 1;
                } else {
                    checkHandler.postDelayed(this, 500);  
                    mScanCnt--;
                }
            } else {
                if (BTBoardConnectActivity.getBtDevice() != null) {
                    finded = 1;
                } else {
                    if (mScanCnt > 0) {
                        checkHandler.postDelayed(this, 1600);  
                    } else {
                        if (mConnectBtBoard != null) {
                            mConnectBtBoard.setText(R.string.bt_state_please_connect);
                        }
                    }
                    mScanCnt = 0;
                }
            }

            if (finded != 0) {
                mScanCnt = 0;
               if (mConnectBtBoard != null) {
                    needReconnect = 1;
                    mConnectBtBoard.setText(R.string.bt_state_connected);
                    mConnectBtBoard.setBackgroundResource(R.drawable.bt_button_connected);
               }

		        mUBLService = BTBoardConnectActivity.getUBLService();
			    mDevice = (Device) BTBoardConnectActivity.getBtDevice();
		        if (mUBLService != null && mDevice != null) {
			        mBtBoardInterface = new BtBoardInterface(mUBLService, mDevice.address);
			        mBtBoardInterface.setListener(mBtBoardListener);
                    if (mBtBoardInterface != null) {
	                    mBtBoardInterface.clearBoardLight();
                        putRecordSetting();
                    }
		        }
            }
        }  
    };  

    public Intent onBtClick() {
        Intent intent = new Intent();

        if (checkHandler != null) {
            checkHandler.removeCallbacks(checkDeviceThread); 
            checkHandler = null;
        }
	    BTBoardConnectActivity.bindUBLService(instance);
        intent.setClass(instance, BTBoardConnectActivity.class);
		Log.e(TAG, "startActivityForResult.");
        return intent;
    }

    public boolean isBluetoothConnected() {
        if ((mUBLService == null) || (mBtBoardInterface == null) || (mDevice == null)) {
            return false;
        } else {
            return true;
        }
    }

	public void onBtDestory() {
	    mBtKeyCaller = null;
        needReconnect = 0;

		// TODO Auto-generated method stub
		if (mUBLService != null && mDevice != null) {
            if (mBtBoardInterface != null) {
	            mBtBoardInterface.clearBoardLight();
            }
            setDeviceName(mDevice.name);
		    mUBLService.disconnectDevice();
        } 
		BTBoardConnectActivity.unbindUBLService(instance);
		mUBLService = null;
        mBtBoardInterface = null;
        mDevice = null;
	}

    public void onConnectActivityReturn(boolean isOk) {
	    mBtKeyCaller = null;

        if (isOk) {
		    mUBLService = BTBoardConnectActivity.getUBLService();
			mDevice = (Device) BTBoardConnectActivity.getBtDevice();
            mScanCnt = 0;

		    if (mUBLService != null && mDevice != null) {
			    mBtBoardInterface = new BtBoardInterface(mUBLService, mDevice.address);
			    mBtBoardInterface.setListener(mBtBoardListener);
			    Log.e(TAG, "BtBoardInterface!");
				setDeviceName(mDevice.name);
                //chessboard.mBtBoardInterface = mBtBoardInterface;
                if (mBtBoardInterface != null) {
	                mBtBoardInterface.clearBoardLight();
                }
                onBtResume();
		    } else {
                mConnectBtBoard.setText(R.string.bt_state_disconnected);
                mConnectBtBoard.setBackgroundResource(R.drawable.bt_button);
            }
        } else {
            mConnectBtBoard.setText(R.string.bt_state_disconnected);
            mConnectBtBoard.setBackgroundResource(R.drawable.bt_button);
        }
    }
	
    protected void deviceConnectStateChange(String deviceAddress, int state) {
        Log.e(TAG, ": deviceConnectStateChange:" + state);

        if (state == BluetoothProfile.STATE_CONNECTED) {
            Log.e(TAG, ": STATE_CONNECTED:" + state);
            if (mDevice != null) {
                setDeviceName(mDevice.name);
            }
        } else if (state == BluetoothProfile.STATE_DISCONNECTED) {
            Log.e(TAG, "STATE_DISCONNECTED:" + state);
            if(mBtBoardInterface != null) {
                mBtBoardInterface.destroy();
            }
            BTBoardConnectActivity.setBtDevice(null);
            mBtBoardInterface = null;
            mUBLService = null; 
            mDevice = null;
            mScanCnt = 0;
			Log.e(TAG, "STATE_DISCONNECTED 2:" + state);
            mConnectBtBoard.setText(R.string.bt_state_disconnected);
            mConnectBtBoard.setBackgroundResource(R.drawable.bt_button);

            reconnectThread();
        }
    }

    private void reconnectThread() {
	    Log.e(TAG, "reconnectThread");
        if (needReconnect == 0) {
	        Log.e(TAG, "reconnectThread isn't need!");
            return;
        }
        needReconnect = 0;
        mScanCnt = 0;

        String deviceName = getDeviceName();
        if ((deviceName == null) || (deviceName.equals(""))) {
	        Log.e(TAG, "deviceName is null");
            mConnectBtBoard.setText(R.string.bt_state_please_connect);
        } else {
            if (BTBoardConnectActivity.bindAndConnectDevice(instance, deviceName) < 0) {
                mConnectBtBoard.setText(R.string.bt_state_please_connect);
            } else {
	            if (checkHandler != null) {
                    checkHandler.removeCallbacks(checkDeviceThread); 
                } else {
                    mConnectBtBoard.setText(R.string.bt_state_connecting);
                }
                checkHandler = new Handler();
                checkHandler.postDelayed(checkDeviceThread, 200);  
                mScanCnt = 21;
            }
        }
    }

    final static BtBoardListener mBtBoardListener = new BtBoardListener() {
        @Override
        public void onRSSI(final String deviceAddress,  final int rssi, final int state) {
            //
        }

        @Override
        public void onConnectionChanged(final String deviceAddress, final int state) {
			Log.e(TAG, "onConnectionChanged before run: " + deviceAddress + " , state : " + state);

            instance.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    myMananger.deviceConnectStateChange(deviceAddress, state);
                }
            });
        }

        @Override
        public void onDeviceNameWrited(int result) {
            instance.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //
                }
            });  
        }

        @Override
        public void onDeviceBattery(final int percent) {
            //
        }

        @Override
        public void onDeviceKey(final int key) {
            instance.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.e("onDeviceKey:", "key value:" + key);
                    if ((mBtKeyCaller != null) && (mBtBoardInterface != null)) {
                        Log.e("mBtKeyCaller:", "key value:" + key);
                        mBtKeyCaller.onBoardKey(key, null);
                        Log.e("mBtKeyCaller:", "finished:" + key);
                    }
                }
            });  
        }

        @Override
        public void onComMsg(final byte[] msg) {
            instance.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ((mBtKeyCaller != null) && (msg != null) && (mBtBoardInterface != null)) {
                        Log.e("onComMsg:", "com value:" + "msg[0]" + msg[0] + 
                            "msg[1]" + msg[1] + "msg[2]" + msg[2]);

                        if (msg[0] == '#') {
                            if (msg[1] == 'P') {
                                mBtKeyCaller.onBoardKey(8, msg);
                            }
                            if (msg[1] == 'I') {
                                mBtKeyCaller.onBoardKey(1, msg);
                            }
                        }
                        Log.e("onComMsg:", "finished:" + msg);
                    } 
                }
            });  
        }

	};
    
    public static void setPromptLightDegree() {
        int[] xPos = new int[6];
        int[] yPos = new int[6];
        int[] colors = new int[6];
        int i;

        if (mBtBoardInterface == null) {
            return;
        }
        for (i = 0; i < 3; i++) {
            xPos[i] = 8 + i;
            yPos[i] = 11;
            colors[i] = mBtBoardInterface.BOARD_LIGHT_BLACK;
        }
        for (i = 3; i < 6; i++) {
            xPos[i] = 8 + i - 3;
            yPos[i] = 12;
            colors[i] = mBtBoardInterface.BOARD_LIGHT_WHITE;
        }
        mBtBoardInterface.setArrayLight(xPos, yPos, colors);
    }

    public void creatDialog() {
        Resources res = instance.getResources();
        AlertDialog.Builder builder = new AlertDialog.Builder(instance);
        builder.setTitle(R.string.boardsetting_title);

        LayoutInflater factory = LayoutInflater.from(instance);
        final View textEntryView = factory.inflate(R.layout.west_chess_boardsetting, null);

        builder.setView(textEntryView);
        builder.setPositiveButton(res.getString(R.string.okButtonText), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //
            }
        });
        builder.setNegativeButton(res.getString(R.string.cancelButtonText), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                //
            }
        });

        lightSeekBar = (SeekBar) textEntryView.findViewById(R.id.ledlight_degree);
        lightSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
                if (mBtBoardInterface != null) {
                    mBtBoardInterface.setBoardLightDegree(1, ledDegree);
                    Log.e(TAG, "set green degree.");
                    setPromptLightDegree();
                    setLedDegreeInfo(ledDegree);
                } else {
                    Log.e(TAG, "set green degree, but null interface.");
                }
                Log.e(TAG, "green stop adjust.");
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                Log.e(TAG, "green start adjust.");
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                ledDegree = ((arg1 * 7) / 100);
                if (ledDegree > 7)
                    ledDegree = 7;
                Log.e(TAG, "green progress:" + arg1);
            }
        });

        int lightDegree = getLedDegreeInfo();
        lightDegree = lightDegree * 100 / 7;
        lightSeekBar.setProgress(lightDegree);

        builder.create().show();
    }

    // add SharedPreferences.  context
    public String getDeviceName() {
        String device;
        SharedPreferences sp = instance.getSharedPreferences("btBoardInfo", Context.MODE_PRIVATE);
        device = sp.getString("name", ""); 
        Log.e(TAG, "getDeviceName:" + device);
        return device; 
    }

    public String setDeviceName(String device) {
        SharedPreferences sp = instance.getSharedPreferences("btBoardInfo", Context.MODE_PRIVATE);
        Log.e(TAG, "setDeviceName:" + device);
        Editor editor = sp.edit();
        editor.putString("name", device);
        editor.commit();
        return device;
    }

    public int getLedDegreeInfo() {
        int value = 0;
        SharedPreferences sp = instance.getSharedPreferences("btBoardInfo", Context.MODE_PRIVATE);
        value = sp.getInt("ledLight", 7);
        Log.e(TAG, "get ledLight degree:" + value);

        return value;
    }

    public int setLedDegreeInfo(int value) {
        SharedPreferences sp = instance.getSharedPreferences("btBoardInfo", Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putInt("ledLight", value);
        Log.e(TAG, "set ledLight degree:" + value);

        editor.commit();
        return value;
    }

    public Runnable putRecordThread = new Runnable() {
        public void run() {
            int value;
            if (mBtBoardInterface == null)
                return;

            value = getLedDegreeInfo();
            mBtBoardInterface.setBoardLightDegree(1, value);
        }
    };

    public void putRecordSetting() {
        settingHandler = new Handler();
        settingHandler.postDelayed(putRecordThread, 800);
    }


    /*
     * change from 8X8 chessboard to 19X19 chessboard, piece move from A to B.
     * the 8X8 chessboard coordinate:
     *          0       8
     *   (0,0)  -----------> X
     *          |
     *          |
     *       8  |
     *         \|/
     *
     * the 19X19 chessboard coordinate:
     * 19X19 chessboard，piece move from A to B.
     *            Y
     *     18  /|\
     *          |
     *          |
     *          |
     *   (0,0)  -----------> X
     *                   18
     * type: -- reserved.
     */
    public static void selectReadyChess(int x, int y) {
        int led_x, led_y, led_color;

        if (mBtBoardInterface == null) {
            return;
        }
        led_x = x * 2 + 2;
        y = 7-y;
        led_y = y * 2 + 2;
        led_color = mBtBoardInterface.BOARD_LIGHT_WHITE;

        Log.e(TAG, "led_x:" + led_x + "led_y:" + led_y);
        mBtBoardInterface.setOneXiangqiSquare(led_x, led_y, led_color);
        return;
    }


    /*
     * change from 8X8 chessboard to 19X19 chessboard, piece move from A to B.
     * the 8X8 chessboard coordinate:
     *          0       8
     *   (0,0)  -----------> X
     *          |
     *          |
     *       8  |
     *         \|/
     *
     * the 19X19 chessboard coordinate:
     * 19X19 chessboard，piece move from A to B.
     *            Y
     *     18  /|\
     *          |
     *          |
     *          |
     *   (0,0)  -----------> X
     *                   18
     * type: -- reserved.
     */
    public static void selectReadyAndGo(int src_x, int src_y, int dst_x, int dst_y) {
        int[] x_arry = new int[2];
        int[] y_arry = new int[2];
        int[] c_arry = new int[2];
        int color_type;

        if (mBtBoardInterface == null) {
            return;
        }
        color_type = mBtBoardInterface.BOARD_LIGHT_WHITE;

        x_arry[0] = src_x * 2 + 2;
        src_y = 7 - src_y;
        y_arry[0] = src_y * 2 + 2;
        c_arry[0] = color_type;

        x_arry[1] = dst_x * 2 + 2;
        dst_y = 7 - dst_y;
        y_arry[1] = dst_y * 2 + 2;
        c_arry[1] = color_type;

        Log.e(TAG, "src x:" + src_x + " src y:" + src_y);
        mBtBoardInterface.setTwoXiangqiSquare(x_arry, y_arry, c_arry);
        return;
    }

}


